const { promisify } = require('util')
const path = require('path')

const download = promisify(require('download-git-repo'))
const open = require('open')

const { vueRepo } = require('../config/repo-config')
const { commandSpawn } = require('../utils/terminal')
const {
  compile,
  writeToFile,
  mkdirSync
} = require('../utils/utils')

// callback -> promisify(函数) -> async await

// 创建项目action
const createProjectAction = async (project, options) => {
  console.log('why helps yoou create your project~')

  // 1.clone项目
  await download(vueRepo, project, {clone: true})

  // 2.执行npm install
  const npm = process.platform === 'win32' ? 'npm.cmd' : 'npm'
  await commandSpawn(npm, ['install'], {cwd: `./${project}`})
  
  // 3.运行npm run server
  await commandSpawn(npm, ['run', 'serve'], {cwd: `./${project}`})

  // 4.打开浏览器
  open('http://localhost:8080/')

}

// 添加组件action
const addComponentAction = async (name, dest) => {
  // 2.编译ejs模板 result
  const result = await compile('vue-component.ejs', {name, lowerName: name.toLowerCase()})

  // 3.将result写入到.vue文件中
  const targetPath = path.resolve(dest, `${name}.vue`)

  mkdirSync(dest)

  writeToFile(targetPath, result)

  // 4.放到对应的文件夹中
}

// 添加组件和路由
const addPageAndRouteAction = async (name, dest) => {
  // 1.编译ejs模板
  const data = {name, lowerName: name.toLowerCase()}
  const pageResult = await compile('vue-component.ejs', data)
  const RouteResult = await compile('vue-router.ejs', data)

  // 2.写入文件
  const basePath = path.resolve(dest, name.toLowerCase())

  const targetPagePath = path.resolve(basePath, `${name}.vue`)
  const targetRoutePath = path.resolve(basePath, 'router.js')

  mkdirSync(basePath)

  writeToFile(targetPagePath, pageResult)
  writeToFile(targetRoutePath, RouteResult)
}

const addStoreAction = async (name, dest) => {
  const storeResult = await compile('vue-store.ejs', {})
  const typesResult = await compile('vue-types.ejs', {})

  const targetStorePath = path.resolve(dest, 'index.js')
  const targetTypesPath = path.resolve(dest, 'types.js')

  mkdirSync(dest)

  writeToFile(targetStorePath, storeResult)
  writeToFile(targetTypesPath, typesResult)
}

module.exports = {
  createProjectAction,
  addComponentAction,
  addPageAndRouteAction,
  addStoreAction
}